/*
 * @Author: wupeiwen <javapeiwen2010@gmail.com>
 * @Date: 2022-03-31 17:32:39
 * @LastEditors: wupeiwen <javapeiwen2010@gmail.com>
 * @LastEditTime: 2023-07-17 17:41:08
 * @FilePath: /tea-garden-web/src/util/storeModules/base-overview.js
 * @Description: 基地概览
 */
/* eslint-disable camelcase */
import { get, get2, post2 } from '@/util/http.js'
import { polygon, center, point, area } from '@turf/turf'
import request from '@/util/request.js'
import { MassifDistribute, EquipmentDistribute, DictList } from '@/util/resData.js'
const formatFarmlandFeature = (data) => {
  const { id, massif_num, massif_boundary } = data
  const feature = polygon(massif_boundary, { id, massif_num })
  feature.properties.center = center(feature).geometry.coordinates
  return feature
}
const formatEquipmentFeature = (data) => {
  if (typeof data.equipment_point === 'string') {
    data.equipment_point = JSON.parse(data.equipment_point)
  }
  const feature = point(data.equipment_point, data)
  return feature
}

export default {
  state: {
    baseInfo: null,
    currentId: '',
    todayWeather: null,
    todayFarming: [],
    allEquipment: [],
    allFarmLand: [],
    query: '',
    queryId: '',
    filterFarmland: [],
    currentFarmlandId: '',
    farmlandInfo: null,
    loading: {
      todayFarming: false,
      filterFarmland: false,
      farmlandInfo: false,
      todayWeather: false,
      allEquipment: false,
      allFarmLand: false,
      realTimeWeatherFromCMA: false,
      token: false,
      realTimeSoilState: false
    },
    // 图层
    layers: { satellite: true, farmland: true, equipment: true },
    // 图例
    legends: { equipment: true, subject: true },
    // 实时天气
    realTimeWeatherFromCMA: null,
    token: null,
    // 实时土壤状态
    realTimeSoilState: null
  },
  getters: {
    formatAllFarmland (state) {
      let features = []
      if (state.allFarmLand.length > 0) {
        features = state.allFarmLand.map((item) => {
          // const polygonList = polygon([item.massif_boundary[0]])
          // const areaMu = area(polygonList)
          // console.log(item.massif_num, parseFloat((areaMu * 0.0015).toFixed(2)))
          // console.log(area(item.massif_boundary[0]))
          return formatFarmlandFeature(item)
        })
      }
      return {
        type: 'FeatureCollection',
        crs: {
          type: 'name',
          properties: {
            name: 'EPSG:4326'
          }
        },
        features
      }
    },
    formatAllEquipment (state) {
      let features = []
      if (state.allEquipment.length > 0) {
        features = state.allEquipment.map((item) => {
          return formatEquipmentFeature(item)
        })
      }
      return {
        type: 'FeatureCollection',
        crs: {
          type: 'name',
          properties: {
            name: 'EPSG:4326'
          }
        },
        features
      }
    }
  },
  mutations: {
    // 设置基地信息
    setBaseInfo (state, payload) {
      state.baseInfo = payload
    },
    // 设置基地id
    setBaseId (state, payload) {
      state.currentId = payload
    },
    // 设置地块列表过滤值
    setQuery (state, payload) {
      let dict = ''
      DictList.data.find(item => {
        if (payload.target.value && item.name.indexOf(payload.target.value) !== -1) {
          dict = item.id
          return true
        }
      })
      state.queryId = dict
      state.query = payload.target.value
    },
    // 设置地块id
    setFarmlandId (state, payload) {
      state.currentFarmlandId = payload
    },
    // 设置地块信息
    setFarmlandInfo (state, payload) {
      state.farmlandInfo = payload
    },
    // 设置图层或图例
    setLayersOrLegends (state, payload) {
      const { obj, key, value } = payload
      state[obj][key] = value
    },
    // 设置通用状态
    setCommonState (state, payload) {
      const { key, value } = payload
      state[key] = value
    },
    // 设置加载状态
    setLoadingState (state, payload) {
      const { key, value } = payload
      state.loading[key] = value
    }
  },
  actions: {
    // 获取基地今日天气
    async getTodayWeather ({ state, commit }) {
      try {
        commit('setLoadingState', { key: 'todayWeather', value: true })
        // 第三方接口获取天气数据
        const getTem = () => request.get('/week?unescape=1&appid=42961365&appsecret=S9dM2OKh&cityid=101210808')
        const res = await getTem()
        // console.log(res)
        const data = res
        // const { data } = await get({ url: '/FarmingBase/TodayWeather', params: { id: state.currentId } })
        // console.log(data)
        commit('setCommonState', { key: 'todayWeather', value: data })
      } catch (error) {
        console.log(error)
      }
      commit('setLoadingState', { key: 'todayWeather', value: false })
    },
    // 获取基地今日农事
    async getTodayFarming ({ state, commit }) {
      try {
        commit('setLoadingState', { key: 'todayFarming', value: true })
        const { data } = await get({ url: '/farming/calendarList' })
        commit('setCommonState', { key: 'todayFarming', value: data })
      } catch (error) {
        console.log(error)
      }
      commit('setLoadingState', { key: 'todayFarming', value: false })
    },
    // 获取基地所有设备
    async getAllEquipment ({ state, commit }) {
      try {
        commit('setLoadingState', { key: 'allEquipment', value: true })
        // const { data } = await get({ url: '/FarmingBase/EquipmentDistribute', params: { id: state.currentId } })
        const { data } = EquipmentDistribute
        commit('setCommonState', { key: 'allEquipment', value: data })
      } catch (error) {
        console.log(error)
      }
      commit('setLoadingState', { key: 'allEquipment', value: false })
    },
    // 获取基地所有地块
    async getAllFarmLand ({ state, commit }) {
      try {
        commit('setLoadingState', { key: 'allFarmLand', value: true })
        // const { data } = await get({ url: '/FarmingBase/MassifDistribute', params: { id: state.currentId } })
        const { data } = MassifDistribute
        // const { data } = await get({ url: `/land/list?breed=${state.queryId}` })
        // const list = data.map(item => {
        //   return {
        //     ...item,
        //     massif_num: item.massifNum,
        //     massif_name: item.massifName,
        //     massif_boundary: JSON.parse(item.massifBoundary)
        //   }
        // })

        commit('setCommonState', { key: 'allFarmLand', value: data })
      } catch (error) {
        console.log(error)
      }
      commit('setLoadingState', { key: 'allFarmLand', value: false })
    },
    // 根据茶叶品种过滤地块
    async filterFarmlandByType ({ state, commit }) {
      try {
        commit('setLoadingState', { key: 'filterFarmland', value: true })
        // const { data } = await get({ url: '/land/list', params: { id: state.currentId, query: state.query } })
        const { data } = await get({ url: `/land/list?breed=${state.queryId}` })
        commit('setCommonState', { key: 'filterFarmland', value: data })
      } catch (error) {
        console.log(error)
      }
      commit('setLoadingState', { key: 'filterFarmland', value: false })
    },
    // 地块信息
    async getFarmlandInfo ({ state, commit }) {
      try {
        commit('setLoadingState', { key: 'farmlandInfo', value: true })
        const { data } = await get({ url: `/land/getDetailById/${state.currentFarmlandId}` })
        const now = new Date()
        const year = now.getFullYear()
        const month = String(now.getMonth() + 1).padStart(2, '0')
        const day = String(now.getDate()).padStart(2, '0')
        const formattedDate = `${year}-${month}-${day}`
        const res = await get({ url: '/farming/detail', params: { planTime: formattedDate, massifId: state.currentFarmlandId } })
        console.log(res.data)
        data.farming_data = res.data
        console.log(data)
        commit('setFarmlandInfo', data)
      } catch (error) {
        console.log(error)
      }
      commit('setLoadingState', { key: 'farmlandInfo', value: false })
    },
    // 实况天气
    async getRealTimeWeatherFromCMA ({ commit }) {
      try {
        commit('setLoadingState', { key: 'realTimeWeatherFromCMA', value: true })
        const { result } = await post2({ url: 'http://data.cma.cn/kbweb/home/live', params: { lat: 28.49150, lon: 119.33990, type: '0' } })
        commit('setCommonState', { key: 'realTimeWeatherFromCMA', value: result.DS[0] })
      } catch (error) {
        console.log(error)
      }
      commit('setLoadingState', { key: 'realTimeWeatherFromCMA', value: false })
    },
    // 获取token
    async getToken ({ commit }) {
      try {
        commit('setLoadingState', { key: 'token', value: true })
        const { data } = await post2({ url: 'http://118.195.198.18:8084/api/v1/getToken', params: { userName: 'meilin_admin', password: 'meilin_admin123456' } })
        commit('setCommonState', { key: 'token', value: 'Bearer ' + data.token })
      } catch (error) {
        console.log(error)
      }
      commit('setLoadingState', { key: 'token', value: false })
    },
    // 获取实时土壤状态
    async getRealTimeSoilState ({ commit, state }) {
      try {
        commit('setLoadingState', { key: 'realTimeSoilState', value: true })
        const { data } = await get2({ url: 'http://118.195.198.18:8084/api/v1/getDeviceSensorData', headers: { Authorization: state.token }, params: { mac: '867124061487187', product_name: '掌控APP', did: '1wXQMWw10r4mq2t3CZ87Iq' } })
        commit('setCommonState', { key: 'realTimeSoilState', value: data })
      } catch (error) {
        console.log(error)
      }
      commit('setLoadingState', { key: 'realTimeSoilState', value: false })
    }
  }
}
